using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WeaponComponent:MonoBehaviour {

	[SerializeField] int _index;
	public int index { get { return _index; } }

	Vector2 previousLocalPosition;
	Vector2 previousOwnerPosition;
	float previousAngle;

	Vector2 localVelocity;
	Vector2 ownerVelocity;
	float angleVelocity;

	float deltaTime;
	float fixedDeltaTime;
	float z;

	Vector3 velocity;

	SpriteRenderer spriteRenderer;
	Transform owner;
	Transform ownerWeapon;
	WeaponSlot ownerSlot;

	void Start() {
		ownerSlot=GetComponentInParent<WeaponSlot>();
		spriteRenderer=GetComponent<SpriteRenderer>();
		ownerWeapon=transform.parent.parent;
		owner=ownerWeapon.parent;
	}

	private void FixedUpdate() {
		fixedDeltaTime=Time.deltaTime;
		ownerVelocity=((Vector2)owner.position-previousOwnerPosition)/Time.deltaTime;
		previousOwnerPosition=owner.position;
	}

	void Update() {
		deltaTime=Time.deltaTime;
		Vector2 localPosition = transform.position-ownerWeapon.position;
		localPosition/=(Angle)ownerWeapon.rotation;

		localVelocity=(localPosition-previousLocalPosition)/Time.deltaTime;
		angleVelocity=(((Angle)transform.rotation).degree-previousAngle)/Time.deltaTime;

		previousLocalPosition=localPosition;
		previousAngle=((Angle)transform.rotation).degree;

		z=ownerSlot.offset.y+localPosition.y;
		velocity=((Vector3.right*localVelocity.x)*(Angle)ownerWeapon.rotation+ownerVelocity);
		velocity.z=localVelocity.y;
	}

	public void TurnIntoDecal(AudioClip sound) {
		GameObject decalObject = DecalController.Create(transform.position,((Angle)transform.rotation).degree,velocity,angleVelocity,spriteRenderer.sprite,z,sound);
		decalObject.transform.localScale=transform.lossyScale;
	}
	public void TurnIntoDecalMuzzleFlash() {
		GameObject decalObject = DecalController.Create(transform.position,((Angle)transform.rotation).degree,transform.right*0.1f,0,spriteRenderer.sprite,0.1f,null,0.1f,0);
		decalObject.transform.localScale=transform.lossyScale;
	}

}
